package com.zzx.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zzx.common.core.domain.entity.SysUser;
import com.zzx.system.service.ISysUserService;
import com.zzx.utils.EntityUtils;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.entity.TGxUser;
import com.zzx.mapper.TGxUserMapper;
import com.zzx.service.TGxUserService;
import com.zzx.config.UserContext;
import com.zzx.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zzx
 * @description 针对表【t_gx_user()】的数据库操作Service实现
 * @createDate 2025-07-06
 */
@Service
public class TGxUserServiceImpl extends ServiceImpl<TGxUserMapper, TGxUser>
        implements TGxUserService {

    @Resource
    private ISysUserService sysUserService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TGxUser param) {

        if (ObjectUtils.isEmpty(param.getGxUserId())) {
            param.setGxUserId(IdUtil.getSnowflakeNextId());
        } else {
            TGxUser dbEntity = this.getBaseMapper().selectById(param.getGxUserId());
            if (dbEntity != null) {
                EntityUtils.mergeNonNullProperties(dbEntity, param);
            }
        }
        this.saveOrUpdate(param);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(TGxUser param) {
        this.removeById(param.getGxUserId());
    }

    @Override
    public IPage<TGxUser> selectBy(TGxUser param) {
        LambdaQueryWrapper<TGxUser> wrapper = new LambdaQueryWrapper<>(TGxUser.class);

        if (!ObjectUtils.isEmpty(param.getGxUserId())) {
            wrapper.eq(TGxUser::getGxUserId, param.getGxUserId());
        }

        // 多租户拦截器会自动添加 company_id 条件
        wrapper.orderByDesc(TGxUser::getCreateTime);

        IPage<TGxUser> tGxUserIPage = this.getBaseMapper().selectPage(
                PageUtils.createPage(param.getPageNum(), param.getPageSize()),
                wrapper
        );

        return tGxUserIPage;
    }

    @Override
    public TGxUser findById(String id) {
        return this.getBaseMapper().selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatchGxById(TGxUser param) {
        LambdaQueryWrapper<TGxUser> wrapper = new LambdaQueryWrapper<>(TGxUser.class);
        // 多租户拦截器会自动添加 company_id 条件
        wrapper.in(TGxUser::getGxId, param.getGxId());
        wrapper.eq(TGxUser::getGxUserId, param.getUserIdList());
        this.remove(wrapper);
    }
}
